<!--
 * @Author: luoyuxiang 398165@qq.com
 * @Date: 2025-03-15 16:28:51
 * @LastEditors: luoyuxiang 398165@qq.com
 * @LastEditTime: 2025-03-25 21:05:45
 * @FilePath: \formula-syn-vue\src\views\project\topic\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item>
          <el-form-item label="名称" prop="searchTerms">
            <el-input
              v-model="queryParams.title"
              placeholder="名称"
              clearable
              @keyup.enter="handleQuery()"
            />
          </el-form-item>

          <el-form-item label="创建时间">
            <el-date-picker
              v-model="queryParams.createTime"
              :editable="false"
              class="!w-[240px]"
              type="daterange"
              range-separator="~"
              start-placeholder="开始时间"
              end-placeholder="截止时间"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button v-hasPerm="['project:topic:add']" type="success" @click="handleOpenDialog()">
          <template #icon><Plus /></template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['project:topic:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon><Delete /></template>
          删除
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />

        <el-table-column key="title" label="名称" prop="title" min-width="350" align="center" />

        <el-table-column
          key="searchTerms"
          label="检索词"
          prop="searchTerms"
          min-width="250"
          align="center"
        />
        <el-table-column key="types" label="类型" prop="types" min-width="60" align="center">
          <template #default="scope">
            <DictLabel v-model="scope.row.types" :code="'topic_type'" />
          </template>
        </el-table-column>

        <el-table-column
          key="tcmNum"
          label="文章数"
          prop="articleCount"
          min-width="60"
          align="center"
        />
        <el-table-column
          key="notNum"
          label="处方数"
          prop="tcmCount"
          min-width="60"
          align="center"
        />
        <el-table-column
          key="createTime"
          label="建立时间"
          prop="createTime"
          min-width="100"
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="400">
          <template #default="scope">
            <el-button
              v-hasPerm="['project:topic:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['project:topic:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
            <el-button
              v-hasPerm="['project:importXml:query']"
              type="warning"
              size="small"
              link
              @click="handleOpenImportXmlData(scope.row)"
            >
              <template #icon><SuitcaseLine /></template>
              文章导入
            </el-button>
            <el-button
              v-hasPerm="['project:topicArticle:query']"
              type="success"
              size="small"
              link
              @click="handleOpenArticletData(scope.row)"
            >
              <template #icon><Pouring /></template>
              文章筛选
            </el-button>
            <el-button
              v-hasPerm="['project:topicArticle:query']"
              type="default"
              size="small"
              link
              @click="handleComparisonOpenDialog(scope.row.id)"
            >
              <template #icon><Reading /></template>
              处方对比
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 我的选题表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      top="3vh"
      width="1050"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="类型" prop="types">
          <dict v-model="formData.types" code="topic_type" />
        </el-form-item>
        <el-form-item label="名称" prop="title">
          <el-input v-model="formData.title" placeholder="名称" />
        </el-form-item>
        <el-form-item label="检索词" prop="searchTerms">
          <el-input v-model="formData.searchTerms" placeholder="检索词" />
        </el-form-item>
        <el-form-item label="简介" prop="content">
          <el-input type="textarea" v-model="formData.content" placeholder="简介" :rows="6" />
        </el-form-item>
        <el-form-item label="实施方案" prop="scheme">
          <el-input type="textarea" v-model="formData.scheme" placeholder="实施方案" :rows="6" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 对比 -->
    <Comparison ref="comparisonRef" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Topic",
  inheritAttrs: false,
});

import TopicAPI, { TopicPageVO, TopicForm, TopicPageQuery } from "@/api/project/topic";
import TopicTcmAPI, {
  TopicTcmPageVO,
  TopicTcmForm,
  TopicTcmPageQuery,
} from "@/api/project/topic-tcm";
import router from "@/router";
import Comparison from "../components/Comparison.vue";

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);
const comparisonRef = ref();

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<TopicPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 我的选题表格数据
const pageData = ref<TopicPageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 我的选题表单数据
const formData = reactive<TopicForm>({});

// 我的选题表单校验规则
const rules = reactive({
  title: [{ required: true, message: "请输入名称", trigger: "blur" }],
  content: [{ required: true, message: "请输入简介", trigger: "blur" }],
  scheme: [{ required: true, message: "请输入实施方案", trigger: "blur" }],
  searchTerms: [{ required: true, message: "请输入检索词", trigger: "blur" }],
  types: [{ required: true, message: "请输入类型", trigger: "blur" }],
});

/** 查询我的选题 */
function handleQuery() {
  loading.value = true;
  TopicAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置我的选题查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开我的选题弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改我的选题";
    TopicAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增我的选题";
  }
}

/** 提交我的选题表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        TopicAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        TopicAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭我的选题弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除我的选题 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      TopicAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

function handleComparisonOpenDialog(id: number) {
  loading.value = true;
  // 获取选题处方
  TopicTcmAPI.getTopicTcms(id)
    .then((data) => {
      const ids = data.map((item) => Number(item.tcmId)).join(",");
      comparisonRef.value.openDialog(ids);
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleOpenImportXmlData(row: TopicPageVO) {
  router.push({
    path: "/project/import-xml",
    query: { id: row.id, title: "【" + row.title + "】选题" },
  });
}

// 打开选题文章数据
function handleOpenArticletData(row: TopicPageVO) {
  router.push({
    path: "/project/topic-article",
    query: { id: row.id, title: "【" + row.title + "】选题" },
  });
}

onMounted(() => {
  handleQuery();
});
</script>
